package com.shen.dimensmaker

import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.math.BigDecimal

/**
 * 作者: Andy
 * 时间: 2016-12-28
 * 描述:
 */
object MakeUtils {
    private const val XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
    private const val XML_RESOURCE_START = "<resources>\r\n"
    private const val XML_RESOURCE_END = "</resources>\r\n"
    private const val XML_DIMEN_TEMPLETE = "<dimen name=\"px_%1\$d\">%2$.2fdp</dimen>\r\n"
    private const val XML_STRING_TEMPLETE = "<string name=\"app_name\">%s</string>\r\n"

    /**
     * 生成的适配目标的记录
     * 比如：适配「1080x720」
     * 留作备份,方便以后扩展更正
     */
    private const val XML_BASE_WIDTH = "<dimen name=\"base_width\">%dpx</dimen>\r\n"
    private const val XML_BASE_HEIGHT = "<dimen name=\"base_height\">%dpx</dimen>\r\n"
    private const val XML_BASE_DPI = "<dimen name=\"base_dpi\">%ddp</dimen>\r\n"

    /** 生成的文件 */
    private const val XML_NAME = "px_dimen.xml"

    /**
     * 获取对应的Dpi级别
     *
     * @param screenDpi
     * @return
     */
    private fun getDpiLevel(screenDpi: Int): String {
        return when {
            screenDpi <= 120 -> "-ldpi"
            screenDpi <= 160 -> "-mdpi"
            screenDpi <= 240 -> "-hdpi"
            screenDpi <= 320 -> "-xhdpi"
            screenDpi <= 480 -> "-xxhdpi"
            screenDpi <= 640 -> "-xxxhdpi"
            else -> "-xxxxhdpi"
        }
    }

    /**
     * 「目标的px」转换为「相应的dp」
     * [pxValue]    目标的px
     * [px2dp]      「一个像素点」对应的「dp值」,基准为「160dpi」 -- 160f / densityDpi
     * [quality]
     *
     */
    fun px2dip(pxValue: Float, px2dp: Float, quality: Float): Float {
        val dpValue = px2dp * pxValue * quality
        val bigDecimal = BigDecimal(dpValue.toDouble())
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toFloat()
    }

    /**
     * 生成「所有的尺寸」数据
     * [type]
     * [quality]
     */
    private fun makeAllDimens(type: DimenTypes, quality: Float): String {
        val px2dp = 160f / type.densityDpi              // 「一个像素点」对应的「dp值」,基准为「160dpi」
        var dpValue: Float
        var temp: String
        val sb = StringBuilder()
        try {
            sb.append(XML_HEADER)
            sb.append(XML_RESOURCE_START)
            // 备份生成的相关信息
            temp = String.format(XML_BASE_WIDTH, type.width)
            sb.append(temp)
            temp = String.format(XML_BASE_HEIGHT, type.height)
            sb.append(temp)
            temp = String.format(XML_BASE_DPI, type.densityDpi)
            sb.append(temp)
            for (i in 0..750) {
                dpValue = px2dip(i.toFloat(), px2dp, quality)
                temp = String.format(XML_DIMEN_TEMPLETE, i, dpValue)
                sb.append(temp)
            }
            sb.append(XML_RESOURCE_END)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sb.toString()
    }

    /**
     * 生成对应的String文件
     *
     * @param name
     * @return
     */
    private fun makeStrings(name: String): String {
        val temp: String
        val sb = StringBuilder()
        try {
            sb.append(XML_HEADER)
            sb.append(XML_RESOURCE_START)
            temp = String.format(XML_STRING_TEMPLETE, name)
            sb.append(temp)
            sb.append(XML_RESOURCE_END)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sb.toString()
    }

    /**
     * 生成的「目标文件夹」
     * 「只需传宽」进来就行
     *
     * @param type     枚举类型
     * @param buildDir 生成的目标文件夹
     */
    fun makeAll(designWidth: Int, type: DimenTypes, buildDir: String) {
        try {
            // 生成规则
            val folderName: String = when {
                type.swWidthDp > 0 -> "values-sw${type.swWidthDp}dp"      // 适配Android 3.2+
                type.isExclude -> return                                  // 暂不生成
                    // 生成「标准的values-mdpi、values-hdpi」后面不跟分辨率
                    // folderName = "values" + getDpiLevel(type.getDensityDpi());
                else -> return                                            // 暂不生成
                    // 生成「带分辨率的values-hdpi-1280x720」
                    // folderName = "values" + getDpiLevel(type.getDensityDpi()) + "-" + type.getHeight() + "x" + type.getWidth();
            }


            // 生成「目标·目录」
            val file = File(buildDir + File.separator + folderName)
            if (!file.exists()) {
                file.mkdirs()
            }

            // 生成「values-xxdpi ...等文件」
            val fos = FileOutputStream(file.absolutePath + File.separator + XML_NAME)
            fos.write(makeAllDimens(type, type.width.toFloat() / designWidth).toByteArray())
            fos.flush()
            fos.close()

            //生成strings.xml文件
            /*FileOutputStream strFos = new FileOutputStream(file.getAbsolutePath() + File.separator + "strings.xml");
            strFos.write(makeStrings(folderName).getBytes());
            strFos.flush();
            strFos.close();*/
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}